<?php

require_once 'Zend/Validate/Abstract.php';


class Ext_Validate_IsImage extends Zend_Validate_Abstract
{

    const FALSE_TYPE   = 'fileMimeTypeFalse';
    const NOT_DETECTED = 'fileMimeTypeNotDetected';
    const NOT_READABLE = 'fileMimeTypeNotReadable';

    protected $_messageTemplates = array(
        self::FALSE_TYPE   => "File '%value%' has a false mimetype of '%type%'",
        self::NOT_DETECTED => "The mimetype of file '%value%' could not be detected",
        self::NOT_READABLE => "File '%value%' is not readable or does not exist",
    );

    protected $_messageVariables = array(
        'type' => '_type'
    );
    
    protected $_type;
    protected $_exts;
    
    public function __construct($exts)
    {
        $this->_exts = $exts;
    }

    /**
     * Defined by Zend_Validate_Interface
     *
     * Returns true if the mimetype of the file matches the given ones. Also parts
     * of mimetypes can be checked. If you give for example "image" all image
     * mime types will be accepted like "image/gif", "image/jpeg" and so on.
     *
     * @param  string $value Real file to check for mimetype
     * @param  array  $file  File data from Zend_File_Transfer
     * @return boolean
     */
    public function isValid($value, $file = null)
    {
        if ($file === null) {
            $file = array(
                'type' => null,
                'name' => $value
            );
        }

        // Is file readable ?
        require_once 'Zend/Loader.php';
        if (!Zend_Loader::isReadable($value)) {
            return $this->_throw($file, self::NOT_READABLE);
        }

        $fileExt  = Ext_Utility_File::getImageType($value);
        //Zend_Debug::dump($fileExt, '$fileExt');exit;
        if (empty($fileExt)) {
            return $this->_throw($file, self::NOT_DETECTED);
        }

        $exts = explode(',', $this->_exts);
        if (in_array($fileExt, $exts)) {
            return true;
        }

        $this->_type = $fileExt;
        return $this->_throw($file, self::FALSE_TYPE);
    }

    /**
     * Throws an error of the given type
     *
     * @param  string $file
     * @param  string $errorType
     * @return false
     */
    protected function _throw($file, $errorType)
    {
        $this->_value = $file['name'];
        $this->_error($errorType);
        return false;
    }
}
